<template>
    <div class="home_container">
        <QuestionItem 
        v-for="question in questionList" 
        :questionData="question" 
        :key="question.no"
        @select="onSelect"/>
        <button @click="submit" class="submit">提交</button>
    </div>
</template>

<script setup>
    import QuestionItem from '@/components/QuestionItem.vue';
    import { reactive } from 'vue';
    import { request } from '@/request';
    import {useAnswerListStore} from '@/stores'

    let questionList = reactive([])
    const answerListStore = useAnswerListStore()

    request.get("/getQuestionList")
    .then((res=>{
        questionList.splice(0, questionList.length)
        questionList.splice(0, 0, ...res.data.questionList)
    }))
    .catch((err)=>{
        console.log("/getQuestionList", "error", err)
    })
    function onSelect(questionNo, selectIndex) {
        for(const question of questionList) {
            if (question.no === questionNo) {
                question.selectIndex = selectIndex
                console.log(question)
            }
        }
    }
    function getAnswerByIndex(optionIndex) {
        switch (optionIndex) {
            case 0:
                return "没有"
            case 1:
                return "很少"
            case 2:
                return "有时"
            case 3:
                return "经常"
            case 4:
                return "总是"
            default:
                return ""
        }
    }
    function submit() {
        const submitAnswers = []
        for(const question of questionList) {
            if (question.selectIndex != -1) {
                submitAnswers.push(question)
            }
        }
        if (submitAnswers.length != questionList.length) {
            alert("请先完成问卷调查")
            return
        }
        answerListStore.answerList.splice(0, answerListStore.answerList.length)
        for(const submitAnswer of submitAnswers) {
            const answer = {no: submitAnswer.no, index: submitAnswer.selectIndex}
            answerListStore.answerList.push(answer)
        }
        let content = "您提交的内容为：\n"
        for (const answer of submitAnswers) {
            content = content + `${answer.no}.${answer.title}
            ${getAnswerByIndex(answer.selectIndex)}\n`
        }
        if (confirm(content)) {
            for (const question of questionList) {
                question.selectIndex = -1
            }
        }
    }
</script>

<style scoped>
    .home_container {
        display: flex;
        flex-direction: column;
    }
    .submit {
        align-self: center;
        margin-top: 50px;
        font-size: 18px;
        padding: 8px 16px;
        background-color: blueviolet;
        border-radius: 5px;
        color: white;
        border-width: 0px;
        cursor: pointer;
    }
</style>